import {
    service
} from '@/utils/request'


const states = {
    qiniuSavePath: 'partner-portal',
    qiniuTokenExpireDate: 300,
    lastRequestTime: 0,
    qiniuToken: {}
}

const mutations = {
    UPDATE_LAST_REQUEST_TIME: (state, time) => {
        state.lastRequestTime = time
    },
    UPDATE_QINIU_TOKEN: (state, token) => {
        state.qiniuToken = token
    }
}

const actions = {
    getQiniuToken({
        commit,
        state
    }) {
        // 判断上次获取的七牛token是否过期
        return new Promise((resolve) => {
            const currentTime = new Date().getTime()
            if (currentTime - state.lastRequestTime > state.qiniuTokenExpireDate * 1000) {
                const uploadToken = Promise.resolve(service.post('/checkin/upload/uploadToken'));
                commit('UPDATE_LAST_REQUEST_TIME', currentTime)
                commit('UPDATE_QINIU_TOKEN', uploadToken)
                resolve(uploadToken)
                return false
            }
            resolve(state.qiniuToken)
            return false
        })
    }
}

export default {
    namespaced: true,
    state: states,
    mutations,
    actions
}